const express = require('express')
const bodyParse = require("body-parser")
const cors = require('cors')
const config = require('./config')
const app = express()
// 链接数据库
const db = require('./db')
// 表单验证中间件
const joi = require("joi")
const router = require('./router')
// 解析Token中间件
const expressJWT = require("express-jwt")
// 配置跨域
app.use(cors())
// 配置解析application/x-www-form-urlencoded 格式的表单数据的中间件
app.use(express.urlencoded({ extended: false }))
app.use(bodyParse.urlencoded({ extended: true }))

// 响应数据的中间件
app.use(function (req, res, next) {
  res.cc = function (err, status = 400) {
    console.log('ccccc', err);
    res.send({
      // 状态
      status,
      // 状态描述，判断 err 是 错误对象 还是 字符串
      message: err instanceof Error ? err.message : err,
    })
  }
  next()
})
// 只有api开头接口不需要进行Token身份验证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] }))

app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "content-type");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Access-Control-Allow-Headers", "content-type,Authorization");
  next();
});

app.use('/api', router.RouterUser)
app.use('/my', router.RouterUserInfo)
app.use('/api', router.RouterArticle)
app.use('/like', router.RouterLike)
app.use('/friend', router.RouterFriendNotice)
// 错误中间件放最后
app.use(function (err, req, res, next) {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.cc(err)
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！', 10415)
  // 未知错误
  res.cc(err)
})

app.listen(3000, () => {
  console.log('api server running at http://127.0.0.1:3000');
})